
import React, {Fragment} from "react";
import {Button, Divider, Dropdown, Icon, Menu, message, Modal} from "antd";
import store from "../../pages/generate/ordinary/Store";
import service from "../../libs/request";

class TableOperation extends React.Component{
    constructor(props) {
        super(props);
        this.state = {}
    }

    showActionType = (type,configUri,configParamsField=[],info={},config={}) => {
        console.log("需要的参数:",configParamsField)
        // 初始化参数
        let configParams = {};
        if (configParamsField.length === 0){ //默认为 id 参数
            if (info["id"]){
                configParams["id"] = (info["id"]).trim();
            }
        }else if (configParamsField[0] === "*"){
            configParams["record"] = JSON.stringify(info);
        }else if(configParamsField === "selected_ids"){
            configParams["selected_ids"] = JSON.stringify(store.selected_ids);
        } else {
            configParamsField.map(item => {
                if (info[item]){
                    configParams[item] = (info[item])
                }
                return true
            })
        }

        if (type === "MODAL"){
            store.showModal(configUri,configParams,config);
        }else if (type === "CONFIRM"){
            console.log("TableOperation",configUri,configParams,config);
            Modal.confirm({
                title: config.title ? config.title : "执行操作确认",
                content: config.content ? config.content : "确定要执行该操作吗?",
                onOk: () => {
                    return service.request({
                        url:configUri,
                        method:"get",
                        params:configParams,
                    }).then(response => {
                        console.log(response.data);
                        if (response.data.code === 200){
                            message.success(response.data.msg ? response.data.msg : "操作成功");
                            store.fetchRecords()
                        }
                    })
                }
            });
        }else if (type === "EXECUTE"){
            service.request({
                url:configUri,
                method:"get",
                params:configParams,
            }).then(response => {
                console.log(response.data);
                if (response.data.code === 200){
                    message.success(response.data.msg ? response.data.msg : "操作成功");
                    store.fetchRecords()
                }
            })
        } else if(type === "LINK"){
            // 创建一个新的URLSearchParams对象
            let params = new URLSearchParams();
            let key;
            // 添加参数到URLSearchParams对象中
            for (key in configParams) {
                params.append(key, configParams[key]);
            }
            // 将参数序列化为查询字符串
            let paramString = params.toString();

            // 如果configUri中已经包含查询字符串，则添加'&'，否则添加'?'
            let delimiter = configUri.includes('?') ? '&' : '?';
            // 将参数字符串添加到configUri中
            let fullUri = configUri + delimiter + paramString;
            window.open(fullUri, '_blank', 'noopener noreferrer')
        } else if(type === "JUMP"){
            window.location.href = configUri;
        }else if(type === "COPY"){
            service.request({
                url:configUri,
                method:"get",
                params:configParams,
            }).then(response => {
                console.log(response.data);
                if (response.data.code === 200){
                    const textarea = document.createElement('textarea');
                    textarea.value = response.data.data;
                    textarea.style.position = 'fixed'; // 避免滚动条抖动
                    document.body.appendChild(textarea);
                    textarea.select();

                    try {
                        document.execCommand('copy');
                        message.success('复制成功');
                    } catch (err) {
                        message.error('复制失败');
                    } finally {
                        document.body.removeChild(textarea);
                    }
                }
            })
        }else {
            message.error("不支持的操作类型:" + type)
        }
    };
    moreMenus = (data,info) => (
        <Menu>
            {
                data.map((item,index) => {
                    let label = item["label"];
                    if(item.hasOwnProperty("new_label")){
                        label = item.new_label;
                    }
                    return (
                        <Menu.Item key={index}>
                            <Button style={{padding: 0}}  type="link" onClick={() => this.showActionType(item["actionType"],item["configUri"],item["configParamsField"],info,item["config"])} >{label}</Button>
                        </Menu.Item>
                    )
                })
            }
        </Menu>
    );

    showConfig = (info,config)=>{
        const displayAction = [];
        let display,show_config,match;
        if(info.hasOwnProperty("display")){
            display = info.display;
            config.forEach(c_item => {
                match = false;
                display.forEach(d_item => {
                    if (d_item.label == c_item.label){
                        match = true;
                        if(d_item.show){
                            displayAction.push(c_item)
                        }
                    }
                });
                if(!match){
                    displayAction.push(c_item)
                }
            });

            show_config = displayAction;
        }else {
            show_config = config;
        }
        return show_config;
    };

    getLabel = (info,config)=>{
        let display,label;
        label = config.label;
        if(info.hasOwnProperty("display")){
            display = info.display;
            display.forEach(d_item => {
                if (d_item.label == config.label){
                    if(d_item.hasOwnProperty("new_label")){
                        label = d_item.new_label;
                    }
                }
            });
        }
        return label;
    };

    render() {
        const {config,info} = this.props;
        // console.log(config,"______________")
        // //拥有权限的操作
        let show_config = this.showConfig(info,config);
        return (
            <span>
                {
                    show_config.map((item,index) => {
                        let label = this.getLabel(info,item);
                        if (item.auth){
                            if (show_config.length > 3){
                                if (index === 3){
                                    //渲染更多
                                    return (
                                        <Dropdown  key={index} overlay={() => this.moreMenus(show_config.slice(3),info,item["config"])} trigger={['click']}>
                                            <Button style={{padding:"0px"}} type={"link"}>
                                                更多 <Icon type="down"/>
                                            </Button>
                                        </Dropdown>
                                    );
                                }else if (index > 3){
                                    return true
                                }
                                else {
                                    return (
                                        <Fragment key={index}>
                                            <Button  type="link" style={{padding: 0}} onClick={() => this.showActionType(item["actionType"],item["configUri"],item["configParamsField"],info,item["config"])} >{label}</Button>
                                            <Divider type="vertical"/>
                                        </Fragment>
                                    )
                                }
                            }else {
                                if (index === (show_config.length-1)){
                                    return <Button key={index} type="link" style={{padding: 0}} onClick={() => this.showActionType(item["actionType"],item["configUri"],item["configParamsField"],info,item["config"])} >{label}</Button>
                                }else {
                                    return (
                                        <Fragment key={index}>
                                            <Button  type="link" style={{padding: 0}} onClick={() => this.showActionType(item["actionType"],item["configUri"],item["configParamsField"],info,item["config"])} >{label}</Button>
                                            <Divider type="vertical"/>
                                        </Fragment>
                                    )
                                }
                            }
                        }

                        return true;
                    })
                }
          </span>
        );
    }
}

export default TableOperation;
